<template>
  <view class="category-container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-input" @click="goSearch">
        <uni-icons type="search" size="18" color="#999"></uni-icons>
        <text class="placeholder">搜索商品</text>
      </view>
    </view>
    
    <!-- 主体内容 -->
    <view class="main-content">
      <!-- 左侧分类导航 -->
      <scroll-view class="nav-scroll" scroll-y>
        <category-nav 
          :categories="categories" 
          :active-id="activeCategoryId"
          @change="changeCategory"
        />
      </scroll-view>
      
      <!-- 右侧商品列表 -->
      <scroll-view 
        class="product-scroll" 
        scroll-y
        @scrolltolower="loadMore"
        :scroll-with-animation="true"
      >
        <!-- 二级分类 -->
        <view class="sub-categories" v-if="subCategories.length > 0">
          <view 
            class="sub-item" 
            v-for="sub in subCategories" 
            :key="sub.id"
            :class="{active: activeSubCategoryId === sub.id}"
            @click="changeSubCategory(sub.id)"
          >
            <text>{{ sub.name }}</text>
          </view>
        </view>
        
        <!-- 商品列表 -->
        <view class="product-list">
          <product-card 
            v-for="product in productList" 
            :key="product.id"
            :product="product"
            @click="viewProduct(product.id)"
          />
        </view>
        
        <!-- 加载状态 -->
        <view class="load-status">
          <uni-load-more 
            :status="loadStatus" 
            :content-text="{
              contentdown: '上拉加载更多',
              contentrefresh: '加载中',
              contentnomore: '没有更多了'
            }" 
          />
        </view>
        
        <!-- 空状态 -->
        <view class="empty-state" v-if="productList.length === 0 && !loading">
          <image 
            class="empty-image" 
            src="/static/images/empty-product.png" 
            mode="aspectFit"
          ></image>
          <text class="empty-text">暂无商品</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import CategoryNav from './components/CategoryNav.vue'
import ProductCard from './components/ProductCard.vue'
//import ProductCard from '../index/components/ProductCard.vue'
// 分类数据
const categories = ref([])
const activeCategoryId = ref('')
const activeSubCategoryId = ref('')

// 商品列表数据
const productList = ref([])
const page = ref(1)
const pageSize = 10
const loadStatus = ref('more') // more / loading / noMore
const loading = ref(false)

// 计算属性
const subCategories = computed(() => {
  const category = categories.value.find(item => item.id === activeCategoryId.value)
  return category ? category.children || [] : []
})

// 页面加载
onLoad(() => {
  // 获取分类数据
  fetchCategories()
})

// 获取分类数据
const fetchCategories = () => {
  loading.value = true
  
  // 模拟API请求
  setTimeout(() => {
    // 模拟数据
    categories.value = [
      {
        id: '1',
        name: '手机数码',
        children: [
          { id: '11', name: '智能手机' },
          { id: '12', name: '平板电脑' },
          { id: '13', name: '智能手表' },
          { id: '14', name: '耳机耳麦' }
        ]
      },
      {
        id: '2',
        name: '电脑办公',
        children: [
          { id: '21', name: '笔记本' },
          { id: '22', name: '台式机' },
          { id: '23', name: '显示器' },
          { id: '24', name: '外设配件' }
        ]
      },
      {
        id: '3',
        name: '家用电器',
        children: [
          { id: '31', name: '电视' },
          { id: '32', name: '空调' },
          { id: '33', name: '冰箱' },
          { id: '34', name: '洗衣机' }
        ]
      },
      {
        id: '4',
        name: '食品生鲜',
        children: [
          { id: '41', name: '新鲜水果' },
          { id: '42', name: '海鲜水产' },
          { id: '43', name: '肉禽蛋品' },
          { id: '44', name: '乳品烘焙' }
        ]
      },
      {
        id: '5',
        name: '美妆个护',
        children: [
          { id: '51', name: '面部护肤' },
          { id: '52', name: '彩妆香水' },
          { id: '53', name: '身体护理' },
          { id: '54', name: '口腔护理' }
        ]
      },
      {
        id: '6',
        name: '服饰鞋包',
        children: [
          { id: '61', name: '男装' },
          { id: '62', name: '女装' },
          { id: '63', name: '鞋靴' },
          { id: '64', name: '箱包' }
        ]
      },
      {
        id: '7',
        name: '运动户外',
        children: [
          { id: '71', name: '运动鞋服' },
          { id: '72', name: '健身器材' },
          { id: '73', name: '户外装备' },
          { id: '74', name: '骑行运动' }
        ]
      }
    ]
    
    // 默认选中第一个分类
    if (categories.value.length > 0) {
      activeCategoryId.value = categories.value[0].id
      // 加载商品数据
      fetchProducts()
    }
    
    loading.value = false
  }, 500)
}

// 获取商品数据
const fetchProducts = () => {
  if (loadStatus.value === 'noMore') return
  
  loadStatus.value = 'loading'
  
  // 模拟API请求延迟
  setTimeout(() => {
    // 模拟数据
    const newData = generateMockProducts(page.value, pageSize, activeCategoryId.value, activeSubCategoryId.value)
    
    if (newData.length === 0) {
      loadStatus.value = 'noMore'
      if (page.value === 1) {
        productList.value = []
      }
    } else {
      productList.value = page.value === 1 ? newData : [...productList.value, ...newData]
      page.value++
      loadStatus.value = newData.length < pageSize ? 'noMore' : 'more'
    }
  }, 800)
}

// 生成模拟商品数据
const generateMockProducts = (page, size, categoryId, subCategoryId) => {
  if (page > 3) return [] // 模拟只有3页数据
  
  const categoryNames = {
    '1': '手机数码', '11': '智能手机', '12': '平板电脑', '13': '智能手表', '14': '耳机耳麦',
    '2': '电脑办公', '21': '笔记本', '22': '台式机', '23': '显示器', '24': '外设配件',
    '3': '家用电器', '31': '电视', '32': '空调', '33': '冰箱', '34': '洗衣机',
    '4': '食品生鲜', '41': '新鲜水果', '42': '海鲜水产', '43': '肉禽蛋品', '44': '乳品烘焙',
    '5': '美妆个护', '51': '面部护肤', '52': '彩妆香水', '53': '身体护理', '54': '口腔护理',
    '6': '服饰鞋包', '61': '男装', '62': '女装', '63': '鞋靴', '64': '箱包',
    '7': '运动户外', '71': '运动鞋服', '72': '健身器材', '73': '户外装备', '74': '骑行运动'
  }
  
  const data = []
  for (let i = 0; i < size; i++) {
    const price = (100 + Math.random() * 900).toFixed(2)
    const originalPrice = (parseFloat(price) * (1 + Math.random() * 0.5)).toFixed(2)
    
    data.push({
      id: `product_${categoryId}_${subCategoryId || 'all'}_${page}_${i}`,
      name: `${categoryNames[subCategoryId] || categoryNames[categoryId]}商品${page}_${i}`,
      price,
      originalPrice,
      image: `/static/product.jpg`,
      sales: Math.floor(Math.random() * 1000),
      rating: (4 + Math.random()).toFixed(1),
      tags: subCategoryId ? [] : ['热销', '新品', '特惠'].slice(0, Math.floor(Math.random() * 3))
    })
  }
  
  return data
}

// 切换分类
const changeCategory = (categoryId) => {
  activeCategoryId.value = categoryId
  activeSubCategoryId.value = ''
  // 重置分页数据
  page.value = 1
  productList.value = []
  loadStatus.value = 'more'
  // 重新加载数据
  fetchProducts()
}

// 切换子分类
const changeSubCategory = (subCategoryId) => {
  activeSubCategoryId.value = subCategoryId
  // 重置分页数据
  page.value = 1
  productList.value = []
  loadStatus.value = 'more'
  // 重新加载数据
  fetchProducts()
}

// 加载更多
const loadMore = () => {
  fetchProducts()
}

// 查看商品详情
const viewProduct = (productId) => {
  uni.navigateTo({
    url: `/pages/product/detail?id=${productId}`
  })
}

// 跳转搜索页
const goSearch = () => {
  uni.navigateTo({
    url: '/pages/product/search'
  })
}
</script>

<style lang="scss" scoped>
.category-container {
  height: calc(100vh - 100rpx);
  display: flex;
  flex-direction: column;
  background-color: $white-bg;
}

.search-bar {
  padding: 20rpx 30rpx;
  background-color: $white-bg;
  border-bottom: 1rpx solid #f5f5f5;
  
  .search-input {
    display: flex;
    align-items: center;
    height: 70rpx;
    background-color: $light-bg;
    border-radius: 35rpx;
    padding: 0 30rpx;
    
    .placeholder {
      font-size: $font-size-28rpx;
      color: #999;
      margin-left: 15rpx;
    }
  }
}

.main-content {
  flex: 1;
  display: flex;
  height: calc(100vh - 115rpx);
}

.nav-scroll {
  width: 180rpx;
  height: 100%;
  background-color: #f8f8f8;
}

.product-scroll {
  flex: 1;
  height: 100%;
  padding: 0 20rpx;
}

.sub-categories {
  display: flex;
  flex-wrap: wrap;
  padding: 20rpx 0;
  
  .sub-item {
    padding: 10rpx 20rpx;
    margin: 0 20rpx 20rpx 0;
    font-size: $font-size-26rpx;
    color: $text-color-666;
    background-color: $light-bg;
    border-radius: 30rpx;
    
    &.active {
      color: $primary-color;
      background-color: rgba(255, 140, 0, 0.1);
    }
  }
}

.product-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.load-status {
  padding: 30rpx 0;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 80rpx 0;
  
  .empty-image {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 30rpx;
    opacity: 0.6;
  }
  
  .empty-text {
    font-size: $font-size-28rpx;
    color: $text-color-666;
  }
}
</style>